#!/usr/bin/python3
# -*- coding: utf8 -*-

import datetime,inspect,jinja2
import os
import re
import shutil
import sys
import time

def cpt(t):
	import json
	print(json.dumps(t,encoding="gbk",ensure_ascii=False,skipkeys=False))

def crun(cmd,errquit=True):
	print("%s------------------%s" %(time.strftime('%Y-%m-%d %H:%M:%S'),cmd))
	fhm=os.system(cmd)
	if fhm!=0 and errquit:
		print("返回值为%d，出错退出" %(fhm))
		sys.exit(1)

def filemtime(wj):
	if not os.path.isfile(wj):
		return 0
	return os.stat(wj).st_mtime

def getarg(*args,**kwargs):
	jg=[]
	for i in range(len(args)):
		x=args[i]
		if len(sys.argv)>i+2:
			if type(args[i])==int:
				x=int(sys.argv[i+2])
			if type(args[i])==float:
				x=float(sys.argv[i+2])
			if type(args[i])==str:
				x=sys.argv[i+2]
			if type(args[i])==bool:
				if sys.argv[i+2].lower() in ["yes","1","true"]:
					x=True
				if sys.argv[i+2].lower() in ["no","0","false"]:
					x=False
		jg.append(x)
	if len(jg)==1:
		return jg[0]
	return jg

def makedirs(d):
	if not os.path.isdir(d):
		os.makedirs(d)

def mkdir(d):
	if not os.path.isdir(d):
		os.mkdir(d)

def unlink(fn):
	if os.path.isfile(fn):
		os.unlink(fn)

class c_commandarg2(object):	#根据命令行参数调用模块及显示相应help
	tcmd={}
	scriptname=""
	def __init__(self,gg,scriptname):
		self.scriptname=scriptname
		for g in gg:
			if (inspect.isfunction(gg[g]) or inspect.isclass(gg[g])) and gg[g].__doc__!=None:
				self.tcmd[g]=gg[g]
		self.tcmd["install"]=self.tcmd.get("install",self.install)
	def main(self):
		if len(sys.argv)>1:
			cmd=sys.argv[1]
		else:
			self.printhelp(self)
			return
		if cmd not in self.tcmd:
			self.printhelp(self)
			print("-------------------------")
			print("%s 命令没找到！" %(cmd))
			return
		cf=self.tcmd[cmd]
		if inspect.isfunction(cf):
			rtn=cf()
		else:
			c=cf()
			rtn=0
			if hasattr(c,"main"):
				rtn=c.main()
		return rtn
	
	@staticmethod
	def printhelp(self):
		'''显示程序说明及命令行、参数信息'''
		print(self.scriptname)
		print("-"*len(self.scriptname)*2)
		maxcmdsize=0
		scmd=[]
		for name in self.tcmd:
			scmd.append(name)
			if len(name)>maxcmdsize:
				maxcmdsize=len(name)
		scmd.sort()
		for name in scmd:
			print("%-*s   %s" %(maxcmdsize,name,self.tcmd[name].__doc__))

	@staticmethod
	def install():
		'''发布本程序到/usr/local/bin'''
		return os.system("rsync -tzuv '%s' /usr/local/bin" %(sys.argv[0]))

def onlyone():	#实例仅运行一次，如果有多于1个则退出运行
	js=0
	for jg in os.popen("ps ax").read().split("\n"):
		if len(sys.argv)>1:
			sj=re.findall("python\s+\S*%s\s+%s" %(sys.argv[0],sys.argv[1]),jg)
		else:
			sj=re.findall("python\s+\S*%s\s*$" %(sys.argv[0]),jg)
		if len(sj)>0:js=js+1
	if js>1:
		print("有多于一个的实例，退出")
		sys.exit(1)

class c_oracle2(object):
	def __init__(self,sconn="",yslj=False,autocommit=False,raiseExp=False):
		global cx_Oracle
		import cx_Oracle
		self.sconn=sconn
		self.connected=False
		self.autocommit=autocommit
		self.raiseExp = raiseExp
		(not yslj) and self.connect()
	def commit(self):
		try:
			self.conn.commit()
		except cx_Oracle.DatabaseError:
			if self.raiseExp:
				raise  # 往上层抛
	def connect(self,sconn=""):
		if sconn!="":
			self.sconn=sconn
			self.connected=False
		if self.connected:
			c=self.conn.cursor()
			try:
				c.execute("select 1 from dual")
			except cx_Oracle.DatabaseError:
				self.connected=False
				if self.raiseExp:
					raise  # 往上层抛
			else:
				return
		try:
			self.conn=cx_Oracle.connect(self.convconn(self.sconn))
		except cx_Oracle.DatabaseError:
			if self.raiseExp:
				raise  # 往上层抛
		else:
			self.c=self.conn.cursor()
			self.connected=True
	def convconn(self,ljc):
		if ljc.find("/")>0:
			return ljc
		f=open("/etc/oraconn.cfg")
		wjnr=f.readlines()
		f.close()
		for i in wjnr:
			s=i.split()
			if len(s)<2:
				continue
			if s[0]==ljc:
				return s[1]
		return ""
	def droptable(self,tablename):
		if self.jg1("select count(1) from user_tables where table_name = upper('%s')" %(tablename))==1:
			self.c.execute("drop table %s purge" %(tablename))
	def execute(self,ssql,**kwargs):
		(not self.connected) and self.connect()
		if not self.connected:
			return
		try:
			c=self.conn.cursor()
			c.execute(ssql,kwargs)
		except cx_Oracle.DatabaseError:
			self.connected=False
			if self.raiseExp:
				raise  # 往上层抛
			return
		return c
	def execute2(self,ssql,**kwargs):
		(not self.connected) and self.connect()
		if not self.connected:
			return
		try:
			jg = []
			c = self.conn.cursor()
			c.execute(ssql, kwargs)
			col = c.description
			for item in c.fetchall():
				dd = {}
				for i in range(len(col)):
					dd[col[i][0]] = item[i]
				jg.append(dd)
		except cx_Oracle.DatabaseError:
			self.connected = False
			if self.raiseExp:
				raise  # 往上层抛
			return
		return jg
	def jg1(self,ssql,**kwargs):
		'''根据sql返回1条结果'''
		(not self.connected) and self.connect()
		if not self.connected:
			return
		try:
			c=self.conn.cursor()
			c.execute(ssql,kwargs)
			jg=c.fetchone()
		except cx_Oracle.DatabaseError:
			self.connected=False
			if self.raiseExp:
				raise  # 往上层抛
			return
		c.close()
		if jg==None:
			return
		if len(jg)==1:
			return jg[0]
		else:
			return jg
	def xg(self,ssql,**kwargs):	#对数据库进行修改，可自动commit
		(not self.connected) and self.connect()
		if not self.connected:
			return
		try:
			c=self.conn.cursor()
			c.execute(ssql,kwargs)
			self.autocommit and self.commit()
		except cx_Oracle.DatabaseError:
			self.connected=False
			if self.raiseExp:
				raise  # 往上层抛
			return
		return True

def start(gg,scriptname,checkonlyone=True):	#启动
	if checkonlyone:onlyone()
	c=c_commandarg2(gg,scriptname)
	c.main()

def db2text():
	'''数据库到文本（仅初期使用，后续应该更新txt，由txt更新到数据库）'''
	db=c_oracle2("cc@cc")
	f=open("field.txt","w")
	for i in db.execute("select ver,colid,colname,coltype,colsize,decpos,info from jjjkzd order by ver,colid"):
		f.write("%s|%d|%s|%s|%d|%d|%s|\n" %(i))
	f.close()
	f=open("filefield.txt","w")
	for i in db.execute("select ver,ftype,colid,colname,must,note from jjjkwj order by ver,ftype,sno"):
		if i[5]==None:
			i=i[:5]+("",)
		f.write("%s|%s|%d|%s|%d|%s|\n" %(i))
	f.close()

def crtsql_field():
	'''根据基础数据生成基金接口字段表jjjkzd的建表sql文件'''
	f=open("../data/field.txt",encoding="gbk")
	td={}
	td["field"]=[]
	for s in f.readlines():
		td["field"].append(s.split("|"))
	t=open("field.tpl","r",encoding="gbk").read()
	print(t)
	tmpl=jinja2.Template(t)
	cf=open("field.sql","w",encoding="gbk")
	print(tmpl.render(td))
	cf.write(tmpl.render(td))
	cf.close()

def crtsql_filefield():
	'''根据基础数据生成基金接口字段表jjjkwj的建表sql文件'''
	f=open("../data/filefield.txt",encoding="gbk")
	td={}
	td["filefield"]=[]
	lasttype=""
	sno=0
	for s in f.readlines():
		s=s.split("|")[:-1]
		if lasttype!=s[1]:
			lasttype=s[1]
			sno=0
		sno=sno+1
		s.append(sno)
		td["filefield"].append(s)
	t=open("filefield.tpl","r",encoding="gbk").read()
	tmpl=jinja2.Template(t)
	cf=open("filefield.sql","w",encoding="gbk")
	print(tmpl.render(td))
	cf.write(tmpl.render(td))
	cf.close()

start(globals(),"处理data数据")
